const WebSocket = require('ws');
;((Ws)=> {
  const server = new Ws.Server({ port: 8000 })
  const init = () => {
    bindEvent();
  }
  function bindEvent() {
    server.on('open', handleOpen);
    server.on('close', handleClose);
    server.on('error', handleError);
    server.on('connection', handleConnection);
  }
  function handleOpen() {
    console.log('WebSocket open');
  }
  function handleClose() {
    console.log('WebSocket close');
  }
  function handleError() {
    console.log('WebSocket error');
  }
  function handleConnection(ws) {
    console.log('WebSocket connection');
    ws.on('message', handleMessage)
  }
  function handleMessage(msg) {
    // console.log(msg.toString());
    server.clients.forEach((c) => { // 遍历客户端
      c.send(msg.toString()) // 客户端广播消息
    })
  }
  init();
})(WebSocket)